const cloud = require('wx-server-sdk')

cloud.init({
	env: cloud.DYNAMIC_CURRENT_ENV,
})

exports.main = async (event) => {
	try {
		const { OPENID } = cloud.getWXContext()
		const { id } = event

		const DB = cloud.database()

		const space = await DB.collection('gn_space').doc(id).get()
		const articles = space?.data.article

		for (let article of articles) {
			DB.collection('gn_article').doc(article._id).remove()
		}

		await DB.collection('gn_space').doc(id).remove()

		const userBeforeUpdate = await DB.collection('gn_user').doc(OPENID).get()
		const newSpace = userBeforeUpdate?.data?.space?.filter((space) => space._id !== id) || []
		await DB.collection('gn_user')
			.doc(OPENID)
			.update({
				data: {
					space: newSpace,
				},
			})
		const userAfterUpdate = await DB.collection('gn_user').doc(OPENID).get()

		return {
			data: userAfterUpdate.data,
			code: 0,
			msg: '删除成功',
		}
	} catch (err) {
		throw err
	}
}
